package ClassicalCryptography;

public class MatrixCipher {
    public String encrypt(String plaintext, int[] key) {
        int column = key.length;
        StringBuilder tempCiphertext = new StringBuilder(plaintext);
        if (plaintext.length() % column != 0) {
            for (int i = 0; i < column - plaintext.length() % column; i++) {
                tempCiphertext.append('*');
            }
        }
        int row = tempCiphertext.length() / column;
        int charIndex = 0;
        char[][] temp = new char[row][column];
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                temp[i][j] = tempCiphertext.charAt(charIndex++);
            }
        }

        StringBuilder res = new StringBuilder(tempCiphertext.length());

        for (int index = 1; index <= column; index++) {
            for (int j = 0; j < column; j++) {
                if (key[j] != index) {
                    continue;
                }
                // 这里有问题
                for (int i = 0; i < row; i++) {
                    res.append(temp[i][j]);
                }
            }
        }
        return res.substring(0);
    }

    public String decrypt(String ciphertext, int[] key) {
        int column = key.length;
        int row = ciphertext.length() / column;

        char[][] temp = new char[row][column];
        int charIndex = 0;

        for (int keyNum = 1; keyNum <= column; keyNum++) {
            for (int index = 0; index < column; index++) {
                if (key[index] != keyNum) {
                    continue;
                }
                for (int i = 0; i < row; i++) {
                    temp[i][index] = ciphertext.charAt(charIndex++);
                }
            }
        }


        StringBuilder res = new StringBuilder(ciphertext.length());
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                if (temp[i][j] != '*') {
                    res.append(temp[i][j]);
                }
            }
        }

        return res.substring(0);

    }

    // 检查key的合法性
    private boolean keyCheck(int[] key) {
        return true;
    }
}
